const { query } = require('../../../../lib/db');
const { authenticateToken } = require('../../../../lib/auth');
const { logVerificationAction } = require('../../../../lib/logger');

async function handler(req, res) {
  try {
    const ticketId = req.query.id;

    if (req.method === 'POST') {
      return await handleVerification(req, res, ticketId);
    }
    
    return res.status(405).json({
      success: false,
      message: '方法不允许'
    });
  } catch (error) {
    console.error('工单验证API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

// 处理工单验证（确认或驳回）
async function handleVerification(req, res, ticketId) {
  const { action, comment } = req.body; // action: 'approve' 或 'reject'

  if (!['approve', 'reject'].includes(action)) {
    return res.status(400).json({
      success: false,
      message: '无效的验证操作'
    });
  }

  try {
    // 检查工单是否存在且需要验证
    const ticketInfo = await query(
      `SELECT user_id, verification_status, verification_requested_by, status 
       FROM tickets WHERE id = ?`, 
      [ticketId]
    );

    if (ticketInfo.length === 0) {
      return res.status(404).json({
        success: false,
        message: '工单不存在'
      });
    }

    const ticket = ticketInfo[0];

    if (ticket.verification_status !== 'pending') {
      return res.status(400).json({
        success: false,
        message: '工单当前不需要验证'
      });
    }

    // 检查验证权限
    const canVerify = await checkVerificationPermission(req.user, ticket);
    if (!canVerify.allowed) {
      return res.status(403).json({
        success: false,
        message: canVerify.message
      });
    }

    // 执行验证操作
    const verificationStatus = action === 'approve' ? 'approved' : 'rejected';
    let newStatus = ticket.status;

    // 如果批准且当前状态是已解决，则关闭工单
    if (action === 'approve' && ticket.status === 'resolved') {
      newStatus = 'closed';
    }
    // 如果驳回，状态回到处理中
    else if (action === 'reject') {
      newStatus = 'in_progress';
    }

    // 更新工单
    await query(
      `UPDATE tickets SET 
        verification_status = ?, 
        verified_by = ?, 
        verified_at = CURRENT_TIMESTAMP,
        verification_comment = ?,
        status = ?,
        last_modified_by = ?,
        updated_at = CURRENT_TIMESTAMP
       WHERE id = ?`,
      [verificationStatus, req.user.id, comment || null, newStatus, req.user.id, ticketId]
    );

    // 记录操作日志
    await logVerificationAction(
      ticketId,
      req.user.id,
      action,
      comment,
      req.headers['x-forwarded-for'] || req.connection.remoteAddress,
      req.headers['user-agent']
    );

    res.status(200).json({
      success: true,
      message: action === 'approve' ? '验证通过' : '验证驳回',
      data: {
        verification_status: verificationStatus,
        status: newStatus
      }
    });
  } catch (error) {
    console.error('处理验证失败:', error);
    res.status(500).json({
      success: false,
      message: '处理验证失败'
    });
  }
}

// 检查验证权限
async function checkVerificationPermission(user, ticket) {
  // 管理员可以验证任何工单
  if (user.role === 'administrator') {
    return { allowed: true };
  }

  // 工单创建者可以验证支持人员提交的解决方案
  if (user.id === ticket.user_id) {
    return { allowed: true };
  }

  // 操作员可以代表用户进行验证
  if (user.role === 'operator') {
    return { allowed: true };
  }

  return { 
    allowed: false, 
    message: '无权限验证此工单' 
  };
}


export default authenticateToken(handler);